﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WanMeiBussinessService;
using WanMeiClient.ProgressExtend;
using WanMeiCommon;
using WanMeiModel;

namespace WanMeiClient.Controllers
{
    public class RaidController : BaseController
    {
        //
        // GET: /Raid/
        private IRaidService _IRaidService;
        private IHeroService _IHeroService;
        private ISkillService _ISkillService;
        public RaidController(IRaidService IRaidService, IHeroService IHeroService, ISkillService ISkillService)
        {
            this._IRaidService = IRaidService;
            this._IHeroService = IHeroService;
            this._ISkillService = ISkillService;
        }

        public ActionResult Index()
        {
            return View();
        }

        [JsonException]
        [CheckLoginFitler]
        public JsonResult GetRaidList()
        {
            List<RaidItem> result = AssemblyData.Instance.GetRaidList();
            return Json(ResultManager.CreateResult<List<RaidItem>>(true, result), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [JsonException]
        [CheckLoginFitler]
        public JsonResult LoadRaidData(int raidId, int heroId)
        {
            //取当前副本的怪
            List<MonsterModel> monsters = _IRaidService.GetMonsterList(raidId);
            if (monsters.Count <= 0)
            {
                return Json(ResultManager.CreateResult(false, ""), JsonRequestBehavior.AllowGet);
            }
            string un = Session["un"].ToString();
            //取当前角色学习的技能列表
            List<StatusSkillItem> skills = AssemblyData.Instance.GetStatusSkillList(heroId, un);
            skills = skills.Where(i => i.Un == un && i.IsStudy == 1 && i.HeroId == heroId).ToList();
            //取角色当前数据信息
            UserRoleModel userInfo = AssemblyData.Instance.GetUserInfoModelResult(heroId, un).UserRoleModel;
            RaidFightManagerModel model = new RaidFightManagerModel(skills, monsters, userInfo);
            //被动技能效果
            model = SkillExtend.UseingPassiveSkills(model);
            model.FightId = Guid.NewGuid().ToString();
            model.RaidId = raidId;
            RedisManager.Set<RaidFightManagerModel>(model.FightId, model, DateTime.Now.AddMinutes(20));
            //由于写战斗时的失误，怪死了。reids给删除了，战斗结果处理，没法搞了，也不能以客户端为准，这里，单独为当前战斗ID存储一份加载怪的数据，用来处理结果。
            RedisManager.Set<List<MonsterModel>>("Monster_" + model.FightId, model.Monsters, DateTime.Now.AddMinutes(20));
            return Json(ResultManager.CreateResult<RaidFightManagerModel>(true, model));
        }

        /// <summary>
        /// 副本，角色对怪使用技能攻击，只有一次性技能，持续性技能客户端处理，每隔几秒进行服务端单独请求
        /// </summary>
        /// <param name="fightId"></param>
        /// <param name="heroId"></param>
        /// <param name="skillId"></param>
        /// <returns></returns>
        [HttpPost]
        [JsonException]
        [CheckLoginFitler]
        public JsonResult RaidFight(string fightId, int heroId, int skillId)
        {
            RaidFightManagerModel fightModel = RedisManager.Get<RaidFightManagerModel>(fightId);
            if (fightModel == null)
                return Json(ResultManager.CreateResult(false, "数据异常"));
            if (fightModel.CurrentRoleInfo.MagicPower < fightModel.RoleSkills.Where(p => p.Id == skillId).FirstOrDefault().NeedMagic)
                return Json(ResultManager.CreateResult(false, "魔力不足"));
            var res = new RaidRoleManager().RoleAttack(fightModel, skillId);
            return Json(ResultManager.CreateResult<RaidFigthResultModel>(true, res));
        }

        /// <summary>
        /// 副本，怪物攻击。TYPE 1普通攻击，2技能攻击
        /// </summary>
        /// <param name="fightId"></param>
        /// <param name="heroId"></param>
        /// <param name="monsterId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpPost]
        [JsonException]
        [CheckLoginFitler]
        public JsonResult RaidMonsterFight(string fightId, int heroId, int monsterId, int type)
        {
            RaidFightManagerModel fightModel = RedisManager.Get<RaidFightManagerModel>(fightId);
            if (fightModel == null)
                return Json(ResultManager.CreateResult(false, "数据异常"));
            var res = new RaidMonsterManager().RaidMonsterAttack(fightModel, monsterId, type);
            return Json(ResultManager.CreateResult<RaidMonsterFightResultModel>(true, res));
        }
        /// <summary>
        /// 副本，角色的DOT独立事件请求
        /// </summary>
        /// <param name="fightId"></param>
        /// <param name="heroId"></param>
        /// <param name="skillId"></param>
        /// <param name="monsterId"></param>
        /// <returns></returns>
        [HttpPost]
        [JsonException]
        [CheckLoginFitler]
        public JsonResult RoleDotSkillFight(string fightId, int heroId, int skillId, int monsterId)
        {
            RaidFightManagerModel fightModel = RedisManager.Get<RaidFightManagerModel>(fightId);
            var res = new RaidRoleManager().RoleDotEvent(fightModel, skillId, monsterId);
            return Json(ResultManager.CreateResult<RaidDotEventResultModel>(true, res));
        }
        /// <summary>
        /// 副本战斗结果处理
        /// </summary>
        /// <param name="fightId"></param>
        /// <param name="heroId"></param>
        /// <returns></returns>
        [HttpPost]
        [JsonException]
        [CheckLoginFitler]
        public JsonResult RaidResultHandle(string fightId, int heroId)
        {
            List<MonsterModel> monsters = RedisManager.Get<List<MonsterModel>>("Monster_" + fightId);
            if (monsters == null)
                return Json(ResultManager.CreateResult(false, "数据异常"));
            RaidFightManagerModel fightModel = RedisManager.Get<RaidFightManagerModel>(fightId);
            if (fightModel == null)
                return Json(ResultManager.CreateResult(false, "数据异常"));
            if(fightModel.FightStatus==0)
                return Json(ResultManager.CreateResult(false, "数据异常"));
            //逻辑：角色获得历练值，经验值，装备道具。
            //取角色当前基本数据信息
            GetRaidFightHandleResultParams param = new GetRaidFightHandleResultParams();
            string un = Session["un"].ToString();
            UserRoleBaseAttributeItem userInfo = AssemblyData.Instance.GetUserInfoModelResult(heroId, un).UserRoleBaseAttributeItem;
            int exValue =0;//副本获得的经验
            int money = 0;//副本获得的金钱
            int povalue = 0;//副本获得的历练值
            if (fightModel.FightStatus == 1)
            {
                exValue = monsters.Sum(p => p.ExValue);
                money = monsters.Sum(p=>p.Money);
                povalue = monsters.Sum(p=>p.PotentialValue);
            }
            else
            {
                exValue = monsters.Sum(p => p.ExValue)/2;
                povalue = monsters.Sum(p=>p.PotentialValue)/2;
            }
            int isLevelUp = 0;
            //获得经验后，传入，获得无论是否升级的最新的角色基本属性
            userInfo = AttributeCalculationExtend.LevelUpCalculation(userInfo, exValue,out isLevelUp);
            userInfo.Money += money;
            userInfo.PotentialValue += povalue;
            //--开始构造BUSSINESS的参数
            param.FightStatus = fightModel.FightStatus;
            param.HeroId = heroId;
            param.Money = userInfo.Money;
            param.PotentialValues = userInfo.PotentialValue;
            param.RaidId = fightModel.RaidId;
            param.RoleCurrentArmor = userInfo.Armor;
            param.RoleCurrentCritical = userInfo.CriticalValue;
            param.RoleCurrentExValues = userInfo.ExValue;
            param.RoleCurrentHealth = userInfo.HealthPoint;
            param.RoleCurrentLevel = userInfo.GameLevel;
            param.RoleCurrentMagic = userInfo.MagicPower;
            param.RoleCurrentAp = userInfo.ApValue;
            param.Un = un;
            //存储更新角色信息，并且根据战斗状态，返回战利品。
            var res = _IRaidService.GetRaidFightHandleResult(param);
            if (res.ProcResult != 1)
            {
                return Json(ResultManager.CreateResult<RaidFightResultModel>(false, res));
            }
            //继续构造业务返回模型
            res.ExValues = exValue;
            res.FightStatus = fightModel.FightStatus;
            res.IsLevelUp = isLevelUp;
            res.Money = money;
            res.PotentialValues = povalue;
            res.GameLevel = userInfo.GameLevel;
            //清除用户信息和背包信息缓存
            var removeList = new List<string>();
            removeList.Add("UserInfoModel_" + heroId + "_" + un);
            removeList.Add("BackPack_" + heroId + "_" + Session["un"].ToString());
            RedisManager.RemoveList(removeList);
            return Json(ResultManager.CreateResult<RaidFightResultModel>(true, res));
            
        }
    }
}
